<script setup>
import { ref, shallowRef, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { useTemplateStore } from '@/stores/template';
// 导入wangEditor
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';

const router = useRouter();
const userStore = useUserStore();
const templateStore = useTemplateStore();

// 检查用户权限
if (!userStore.isAdmin) {
  router.push('/');
}

// 表单数据
const templateForm = ref({
  name: '',
  content: '',
  category: ''
});

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 编辑器内容
const editorValue = ref('');

// 编辑器配置
const editorConfig = {
  placeholder: '请输入模板内容...',
  MENU_CONF: {}
};

// 表单验证
const formErrors = ref({
  name: '',
  content: ''
});

// 提交状态
const loading = ref(false);
const error = ref(null);

// 验证表单
const validateForm = () => {
  let isValid = true;
  formErrors.value = {
    name: '',
    content: ''
  };
  
  if (!templateForm.value.name.trim()) {
    formErrors.value.name = '模板名称不能为空';
    isValid = false;
  }
  
  if (!editorValue.value.trim()) {
    formErrors.value.content = '模板内容不能为空';
    isValid = false;
  }
  
  return isValid;
};

// 创建模板
const createTemplate = async () => {
  if (!validateForm()) return;
  
  loading.value = true;
  error.value = null;
  
  try {
    const templateId = await templateStore.createTemplate(
      templateForm.value.name,
      editorValue.value,
      templateForm.value.category || null
    );
    
    if (templateId) {
      // 使用返回的模板ID进行路由跳转
      router.push(`/templates/${templateId}`);
    }
  } catch (err) {
    console.error('Failed to create template:', err);
    error.value = '创建模板失败，请稍后再试';
  } finally {
    loading.value = false;
  }
};

// 取消创建
const cancelCreate = () => {
  router.push('/templates');
};

// 组件卸载前清理
onBeforeUnmount(() => {
  // 销毁编辑器
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<template>
  <div class="template-create-container">
    <div class="template-create-header">
      <h1 class="page-title">创建新模板</h1>
      <button @click="cancelCreate" class="cancel-btn">
        取消
      </button>
    </div>
    
    <div v-if="error" class="error-message">
      {{ error }}
    </div>
    
    <form @submit.prevent="createTemplate" class="template-form">
      <div class="form-group">
        <label for="template-name">模板名称 <span class="required">*</span></label>
        <input 
          type="text" 
          id="template-name" 
          v-model="templateForm.name" 
          placeholder="输入模板名称"
          :class="{ 'input-error': formErrors.name }"
        />
        <p v-if="formErrors.name" class="error-text">{{ formErrors.name }}</p>
      </div>
      
      <div class="form-group">
        <label for="template-category">分类</label>
        <input 
          type="text" 
          id="template-category" 
          v-model="templateForm.category" 
          placeholder="输入模板分类（可选）"
        />
        <p class="help-text">分类可以帮助用户更快地找到合适的模板</p>
      </div>
      
      <div class="form-group">
        <label for="template-content">模板内容 <span class="required">*</span></label>
        <!-- 工具栏 -->
        <Toolbar
          style="border-bottom: 1px solid #ccc"
          :editor="editorRef"
          :defaultConfig="editorConfig"
          mode="default"
        />
        <!-- 编辑器 -->
        <Editor
          style="height: 400px; overflow-y: hidden;"
          v-model="editorValue"
          :defaultConfig="editorConfig"
          mode="default"
          @onCreated="editorRef = $event"
        />
        <p v-if="formErrors.content" class="error-text">{{ formErrors.content }}</p>
      </div>
      
      <div class="form-actions">
        <button 
          type="button" 
          @click="cancelCreate" 
          class="btn-secondary"
        >
          取消
        </button>
        <button 
          type="submit" 
          class="btn-primary" 
          :disabled="loading"
        >
          {{ loading ? '创建中...' : '创建模板' }}
        </button>
      </div>
    </form>
  </div>
</template>

<style scoped>
.template-create-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 2rem 1rem;
}

.template-create-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.page-title {
  font-size: 1.875rem;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.cancel-btn {
  padding: 0.5rem 1rem;
  background-color: transparent;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 0.875rem;
  color: #4b5563;
  cursor: pointer;
  transition: all 0.2s;
}

.cancel-btn:hover {
  background-color: #f3f4f6;
}

.error-message {
  padding: 1rem;
  background-color: #fee2e2;
  border: 1px solid #ef4444;
  border-radius: 4px;
  color: #b91c1c;
  margin-bottom: 1.5rem;
}

.template-form {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.form-group label {
  font-size: 0.875rem;
  font-weight: 500;
  color: #4b5563;
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.required {
  color: #ef4444;
}

.form-group input {
  padding: 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 1rem;
  width: 100%;
}

.form-group input:focus {
  outline: none;
  border-color: #4f46e5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
}

.input-error {
  border-color: #ef4444 !important;
}

.error-text {
  font-size: 0.75rem;
  color: #ef4444;
  margin-top: 0.25rem;
}

.help-text {
  font-size: 0.75rem;
  color: #6b7280;
  margin-top: 0.25rem;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1rem;
}

.btn-primary,
.btn-secondary {
  padding: 0.75rem 1.5rem;
  border-radius: 4px;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-primary {
  background-color: #4f46e5;
  color: white;
  border: 1px solid #4f46e5;
}

.btn-primary:hover:not(:disabled) {
  background-color: #4338ca;
}

.btn-primary:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-secondary {
  background-color: white;
  color: #4b5563;
  border: 1px solid #d1d5db;
}

.btn-secondary:hover {
  background-color: #f3f4f6;
}
</style>